package com.yunfeng.supercall.httputils;

import java.io.File;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.text.TextUtils;

import com.yunfeng.supercall.BuildConfig;
import com.yunfeng.supercall.httputils.CustomMultipartEntity.ProgressListener;

public class UploadUtilsAsyncTask extends AsyncTask<String, Long, String> {
	private OnUplaodListener mListener;

	public UploadUtilsAsyncTask(OnUplaodListener listener) {
		mListener = listener;
	}

	public static interface OnUplaodListener {
		void onUpload(long current, long total, long progress);

		void onUploadSuccess(String data);

		void onUploadError(String error);
	}

	private long totalSize;

	@Override
	protected void onPreExecute() {
	}

	@Override
	protected String doInBackground(String... params) {
		String serverResponse = null;

		String url = params[1];
		String filePath = params[0];
		HttpClient httpClient = new DefaultHttpClient();
		HttpContext httpContext = new BasicHttpContext();
		HttpPost httpPost = new HttpPost(url);

		try {
			CustomMultipartEntity multipartContent = new CustomMultipartEntity(
					new ProgressListener() {
						@Override
						public void transferred(long num) {
							// try {
							// Thread.sleep(300);
							// } catch (InterruptedException e) {
							// // TODO Auto-generated catch block
							// e.printStackTrace();
							// }
							publishProgress(num, totalSize,
									(long) ((num / (float) totalSize) * 100));

						}
					});

			// We use FileBody to transfer an image
			multipartContent.addPart("data", new FileBody(new File(filePath)));
			totalSize = multipartContent.getContentLength();

			// Send it
			httpPost.setEntity(multipartContent);
			HttpResponse response = httpClient.execute(httpPost, httpContext);
			serverResponse = EntityUtils.toString(response.getEntity());

		} catch (Exception e) {
			e.printStackTrace();
		}

		return serverResponse;
	}

	@Override
	protected void onProgressUpdate(Long... progress) {
		mListener.onUpload(progress[0], progress[1], progress[2]);
	}

	@Override
	protected void onPostExecute(String result) {
		if (BuildConfig.DEBUG) {
			System.out.println("result: " + result);
		}
		if (TextUtils.isEmpty(result)) {
			mListener.onUploadError("网络连接失败，请重试");
			return;
		}
		try {
			JSONObject json = new JSONObject(result);
			if (json.has("Code")) {
				int code = json.getInt("Code");
				if (code == 0) {
					mListener.onUploadSuccess(json.getString("Data"));
				} else {
					mListener.onUploadError(json.getString("Data"));
				}
			}

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@Override
	protected void onCancelled() {
		System.out.println("cancle");
	}

}